# TradingAgents/graph/conditional_logic.py

from tradingagents.agents.utils.agent_states import AgentState


class ConditionalLogic:
    """Handles conditional logic for determining graph flow."""

    def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):
        """Initialize with configuration parameters."""
        self.max_debate_rounds = max_debate_rounds
        self.max_risk_discuss_rounds = max_risk_discuss_rounds

    def should_continue_market(self, state: AgentState):
        """Determine if market analysis should continue."""
        messages = state["messages"]
        last_message = messages[-1]
        if last_message.tool_calls:
            return "tools_market"
        return "Msg Clear Market"

    def should_continue_social(self, state: AgentState):
        """Determine if social media analysis should continue."""
        messages = state["messages"]
        last_message = messages[-1]
        if last_message.tool_calls:
            return "tools_social"
        return "Msg Clear Social"

    def should_continue_news(self, state: AgentState):
        """Determine if news analysis should continue."""
        messages = state["messages"]
        last_message = messages[-1]
        if last_message.tool_calls:
            return "tools_news"
        return "Msg Clear News"

    def should_continue_fundamentals(self, state: AgentState):
        """Determine if fundamentals analysis should continue."""
        messages = state["messages"]
        last_message = messages[-1]
        if last_message.tool_calls:
            return "tools_fundamentals"
        return "Msg Clear Fundamentals"

    def should_continue_debate(self, state: AgentState) -> str:
        """Determine if debate should continue."""

        # 添加安全检查，防止无限循环
        count = state.get("investment_debate_state", {}).get("count", 0)
        current_response = state.get("investment_debate_state", {}).get("current_response", "")
        
        if count >= 2 * self.max_debate_rounds:
            return "Research Manager"
            
        # 更健壮的状态检查
        if current_response and current_response.startswith("Bull"):
            return "Bear Researcher"
        return "Bull Researcher"

    def should_continue_risk_analysis(self, state: AgentState) -> str:
        """Determine if risk analysis should continue."""
        
        # 添加安全检查，防止无限循环
        count = state.get("risk_debate_state", {}).get("count", 0)
        latest_speaker = state.get("risk_debate_state", {}).get("latest_speaker", "")
        
        if count >= 3 * self.max_risk_discuss_rounds:
            return "Risk Judge"
            
        # 更健壮的状态检查 - 使用中文标识符
        if latest_speaker and latest_speaker.startswith("风险型"):
            return "Safe Analyst"
        if latest_speaker and latest_speaker.startswith("保守型"):
            return "Neutral Analyst"
        return "Risky Analyst"
